package com.haust.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haust.commons.exception.DaoException;
import com.haust.commons.pojo.HaustResult;
import com.haust.content.service.ContentService;
import com.haust.dao.RedisDao;
import com.haust.mapper.TbContentMapper;
import com.haust.pojo.TbContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private TbContentMapper contentMapper;

    @Autowired
    private RedisDao redisDao;

    @Value("${Haust.incr.content}")
    private String contentKey;

    /**
     * 根据种类Id 查询具体的广告内容信息
     *
     * @param categoryId 种类Id
     * @return
     */
    @Override
    public HaustResult selectTbContentAllByCategoryId(Long categoryId) {
        QueryWrapper<TbContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        List<TbContent> list = contentMapper.selectList(queryWrapper);
        return HaustResult.ok(list);
    }


    /**
     * 新增  广告内容
     *
     * @param content
     * @return
     */
    @Override
    @Transactional(rollbackFor = {DaoException.class})
    public HaustResult insertTbContent(TbContent content) {
        Long incr = null;
        try {
            redisDao.incr(contentKey);
        } catch (Exception e) {
            e.printStackTrace();
            return HaustResult.error("服务忙，稍后再试！");
        }
        content.setId(incr);
        Date now = new Date();
        content.setUpdated(now);
        content.setCreated(now);
        try {
            contentMapper.insert(content);
        } catch (RuntimeException e) {
            throw new DaoException("服务忙，稍后再试！");
        }
        return HaustResult.ok();
    }


    /**
     * 根据id删除 对应的 广告内容
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {DaoException.class})
    public HaustResult deleteContentByIds(Long id) {

        try {
            contentMapper.deleteById(id);
        } catch (RuntimeException e) {
            throw new DaoException("服务忙，稍后再试！");
        }

        return HaustResult.ok();
    }
}
